import threading
import types


def request():
    return Request()


class Request:

    # 全局实例
    # local = threading.local()
    local = {"request": {}}

    _instance = None

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super(Request, cls).__new__(cls, *args, **kwargs)
        return cls._instance

    """ def __init__(self) -> types.NoneType:
        print("local", self.local)
        if not hasattr(self.local, "request"):
            print("不存在request属性")
            self.local.request = {}
        else:
            print("存在request属性")
        return None """

    async def init(self, request_obj=None):
        if request_obj is None:
            return None
        request = {}
        request["json"] = await request_obj.json()
        request["post"] = await request_obj.post()
        # request['header'] = await request_obj.header()
        self.local["request"] = request
        return None

    def json(self, key: str = "", default=None):
        request = self.local.get("request", {})
        data = request.get("json", {})
        if key != "":
            return data.get(data, default)
        return data

    def post(self, key: str = "", default=None):
        request = self.local.get("request", {})
        data = request.post
        if key != "":
            return data.get(data, default)
        return data

    def get(self, key: str = "", default=None):
        request = self.local.get("request", {})
        data = request.query
        if key != "":
            return data.get(data, default)
        return data
